#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "wpacli.h"
#include<stdatomic.h>







#define CONFIG_CTRL_IFACE_CLIENT_DIR "/tmp"
#define CONFIG_CTRL_IFACE_CLIENT_PREFIX "wpa_ctrl_"
#define WPA_I_PATH "/var/run/wpa_supplicant/wlan0"

volatile unsigned int  IsScanOK=0;
// 自定义事件处理函数
void event_handler(const char *event) {
    printf("[EVENT] %s\n", event);
    
    if (strstr(event, "CONNECTED")) {
        printf("=== 网络连接成功 ===\n");
    } else if (strstr(event, "DISCONNECTED")) {
        printf("!!! 网络连接丢失 !!!\n");
    }
    else if (strstr(event,"CTRL-EVENT-SCAN-RESULTS"))
    {
        IsScanOK=1;
    }
}
int main(int argc, char *argv[])
{ 
    int result=0;
    char reply[4096];
    int reply_len=sizeof(reply)+1;


    wpa_conn *conn=wpa_connect(WPA_I_PATH, 1,&result);

    if (!conn) {
     printf("连接失败: %s\n", wpa_strerror(result));
        return -1;
    }   
  conn->event_callback=event_handler;
    if (wpa_send_command(conn, "ATTACH", reply, &reply_len) == WPA_OK) //启用事件监听
     {
         printf("Recv:\n%s\n", reply);
     }
    if (wpa_send_command(conn, "SCAN", reply, &reply_len) == WPA_OK) 
    {
        printf("Recv:\n%s\n", reply);
    }

    int attempt = 0;
    int MAX_RETRIES=10;
    for (; attempt < MAX_RETRIES; attempt++) 
    {
        if (atomic_load(&IsScanOK))// 原子读取
         {
            memset(reply, 0, sizeof(reply));
            reply_len = sizeof(reply)-1; // 保留终止符空间            
            int ret = wpa_send_command(conn, "SCAN_RESULTS", reply, &reply_len);
            if (ret == WPA_OK) 
            {
                printf("[SUCCESS] Scan results:\n%s\n", reply);
            } 
            else
             {
                printf("Command failed: %s", wpa_strerror(ret));
            }
            break; // 无论成功失败都退出
        }
        usleep(500 * 1000); // 毫秒转微秒
    }
        wpa_disconnect(conn);
        return 0;

}